<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Service Worker 示例</title>
    <link rel="stylesheet" href="/service-worker/index.css"></link>
</head>
<body>
    <div class="container">
        <h1>Service Worker 示例</h1>
        <p>此示例演示 Service Worker 的核心功能：资源缓存、离线支持和后台同步。</p>
        
        <div class="status-bar">
            <div>
                当前状态: <span id="status" class="online-status">正在检测...</span>
            </div>
            <div>
                Service Worker: <span id="sw-status">未注册</span>
            </div>
        </div>
        
        <div class="card">
            <h3>缓存控制</h3>
            <div class="controls">
                <button id="registerBtn">注册 Service Worker</button>
                <button id="updateBtn">更新缓存</button>
                <button id="clearCacheBtn">清除缓存</button>
                <button id="unregisterBtn">注销 Service Worker</button>
            </div>
            <div id="cacheInfo" class="hidden">
                <h4>已缓存的资源:</h4>
                <div class="cache-list" id="cacheList"></div>
            </div>
        </div>
        
        <div class="card">
            <h3>API 测试</h3>
            <div class="api-test">
                <button id="fetchBtn">获取API数据</button>
                <button id="syncBtn">后台同步</button>
                <button id="offlineBtn">模拟离线</button>
            </div>
            <div id="apiResponse"></div>
        </div>
        
        <div class="card">
            <h3>操作日志</h3>
            <div class="log-container" id="logContainer"></div>
        </div>
    </div>

    <script>
        // 日志记录函数
        function log(message) {
            const logContainer = document.getElementById('logContainer');
            const logEntry = document.createElement('div');
            logEntry.className = 'log-entry';
            
            const now = new Date();
            const timeString = `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}:${now.getSeconds().toString().padStart(2, '0')}`;
            
            logEntry.innerHTML = `<span class="log-time">[${timeString}]</span> ${message}`;
            logContainer.appendChild(logEntry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }

        // 更新网络状态显示
        function updateNetworkStatus() {
            const statusElement = document.getElementById('status');
            if (navigator.onLine) {
                statusElement.textContent = '在线';
                statusElement.className = 'online-status';
            } else {
                statusElement.textContent = '离线';
                statusElement.className = 'offline-status';
            }
        }

        // 注册 Service Worker
        async function registerServiceWorker() {
            if (!('serviceWorker' in navigator)) {
                log('错误: 此浏览器不支持 Service Worker');
                return;
            }

            try {
                const registration = await navigator.serviceWorker.register('sw.js');
                log('Service Worker 注册成功');
                
                // 更新状态显示
                document.getElementById('sw-status').textContent = '已注册';
                
                // 监听更新
                registration.addEventListener('updatefound', () => {
                    log('检测到 Service Worker 更新');
                });
            } catch (error) {
                log(`注册失败: ${error.message}`);
            }
        }

        // 注销 Service Worker
        async function unregisterServiceWorker() {
            if (!navigator.serviceWorker) {
                log('错误: 此浏览器不支持 Service Worker');
                return;
            }

            const registrations = await navigator.serviceWorker.getRegistrations();
            for (let registration of registrations) {
                await registration.unregister();
                log('Service Worker 已注销');
                document.getElementById('sw-status').textContent = '未注册';
            }
        }

        // 清除缓存
        async function clearCache() {
            try {
                const cacheNames = await caches.keys();
                await Promise.all(cacheNames.map(cacheName => caches.delete(cacheName)));
                log('缓存已清除');
                document.getElementById('cacheList').innerHTML = '';
                document.getElementById('cacheInfo').classList.add('hidden');
            } catch (error) {
                log(`清除缓存失败: ${error.message}`);
            }
        }

        // 显示缓存内容
        async function displayCacheContents() {
            const cacheList = document.getElementById('cacheList');
            cacheList.innerHTML = '';
            
            const cacheNames = await caches.keys();
            for (const cacheName of cacheNames) {
                const cache = await caches.open(cacheName);
                const requests = await cache.keys();
                
                requests.forEach(request => {
                    const li = document.createElement('div');
                    li.textContent = request.url;
                    cacheList.appendChild(li);
                });
            }
            
            if (cacheList.children.length > 0) {
                document.getElementById('cacheInfo').classList.remove('hidden');
            }
        }

        // 模拟API请求
        async function fetchData() {
            const apiResponse = document.getElementById('apiResponse');
            apiResponse.innerHTML = '请求中...';
            
            try {
                // 使用一个模拟API
                const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
                const data = await response.json();
                apiResponse.innerHTML = `
                    <strong>获取成功:</strong>
                    <pre>${JSON.stringify(data, null, 2)}</pre>
                `;
                log('API 数据获取成功');
            } catch (error) {
                apiResponse.innerHTML = `<strong>错误:</strong> ${error.message}`;
                log(`API 请求失败: ${error.message}`);
            }
        }

        // 模拟后台同步
        function triggerBackgroundSync() {
            if (!navigator.serviceWorker) {
                log('错误: 此浏览器不支持后台同步');
                return;
            }

            navigator.serviceWorker.ready.then(registration => {
                registration.sync.register('sync-data').then(() => {
                    log('后台同步已注册');
                }).catch(err => {
                    log(`后台同步注册失败: ${err}`);
                });
            });
        }

        // 模拟离线状态
        function simulateOffline() {
            log('模拟离线模式 - 后续请求将使用缓存');
            // 在实际应用中，这里会触发离线状态逻辑
            document.getElementById('status').textContent = '离线 (模拟)';
            document.getElementById('status').className = 'offline-status';
        }

        // 更新Service Worker
        function updateServiceWorker() {
            if (navigator.serviceWorker) {
                navigator.serviceWorker.getRegistration().then(registration => {
                    if (registration) {
                        registration.update();
                        log('已触发 Service Worker 更新');
                    }
                });
            }
        }

        // 初始化
        document.addEventListener('DOMContentLoaded', () => {
            // 添加事件监听器
            document.getElementById('registerBtn').addEventListener('click', registerServiceWorker);
            document.getElementById('unregisterBtn').addEventListener('click', unregisterServiceWorker);
            document.getElementById('clearCacheBtn').addEventListener('click', clearCache);
            document.getElementById('fetchBtn').addEventListener('click', fetchData);
            document.getElementById('syncBtn').addEventListener('click', triggerBackgroundSync);
            document.getElementById('offlineBtn').addEventListener('click', simulateOffline);
            document.getElementById('updateBtn').addEventListener('click', updateServiceWorker);
            
            // 初始网络状态检测
            updateNetworkStatus();
            window.addEventListener('online', updateNetworkStatus);
            window.addEventListener('offline', updateNetworkStatus);
            
            // 检查是否已有注册的Service Worker
            if (navigator.serviceWorker) {
                navigator.serviceWorker.getRegistration().then(registration => {
                    if (registration) {
                        document.getElementById('sw-status').textContent = '已注册';
                        displayCacheContents();
                    }
                });
            }
            
            log('应用已初始化');

            // 添加 Service Worker 消息监听
          if (navigator.serviceWorker) {
            navigator.serviceWorker.addEventListener('message', event => {
              const { type, message } = event.data;
              
              switch (type) {
                  // case 'LOG':
                  //     log(message);
                  //     break;
                  // case 'SYNC_COMPLETE':
                  //     log(message);
                  //     // 可以在这里添加其他同步完成后的操作
                  //     break;
                  default:
                      log(`Service Worker: ${message}`);
                      }
                  });
            }
        });
    </script>
</body>
</html>